package org.amse.korovkin.ciphering.model.cipher.util;

import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

/**
 *
 * @author Mikhail Korovkin
 */
public class TextWork {

    private TextWork() {
    }

    public static List<Integer> readText(String inputFile)
            throws FileNotFoundException, IOException {
        List<Integer> result = new ArrayList<Integer>();
        DataInputStream dis = new DataInputStream(new FileInputStream(inputFile));
        int x = 0;
        while ((x = dis.read())!= -1) {
            result.add(MathUtil.getPosByte((byte)x));
        }
        dis.close();
        return result;
    }
    public static void writeText(String inputFile, List<Integer> source)
            throws FileNotFoundException, IOException {
        DataOutputStream dos = new DataOutputStream(new FileOutputStream(inputFile));
        for (int i = 0; i < source.size(); i++) {
            try {
                dos.writeByte(MathUtil.getSignedByte(source.get(i)));
            } catch (IllegalArgumentException ex) {
                System.out.println(ex + " (in " + i + ")");
                dos.writeByte(MathUtil.getSignedByte(0));
            }
        }
        dos.close();
    }

    public static List<List<Integer>> getBlocks(List<Integer> plainText, int blockSize) {
        List<List<Integer>> result = new ArrayList<List<Integer>>();
        while (plainText.size() > blockSize) {
            List<Integer> block = new ArrayList<Integer>();
            for (int i = 0; i < blockSize; i++) {
                block.add(plainText.get(i));
            }
            plainText.subList(0, blockSize).clear();
            result.add(block);
        }
        List<Integer> lastBlock = new ArrayList<Integer>();
        for (int i = 0; i < blockSize; i++) {
            if (plainText.size() > i){
                lastBlock.add(plainText.get(i));
            } else {
                lastBlock.add((int)0);
            }
        }
        plainText.clear();
        result.add(lastBlock);
        return result;
    }

    public static String cutComma(String s) {
        if (s.charAt(s.length()-1) == ',') {
            String[] subString = s.split(",");
            return(subString[0]);
        } else return s;
    }
}
